<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入交付小组名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['course:PayGroup:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['course:PayGroup:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="PayGroupList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="标识" align="center" prop="id" /> -->
      <el-table-column label="所属交付小组" align="center" prop="name" />
<!--      <el-table-column label="课程分类" align="center" prop="classTypeName" />-->
      <el-table-column label="接单类型" align="center" prop="orderType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.c_order_type" :value="scope.row.orderType" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="组长id" align="center" prop="userGroupId" /> -->
      <el-table-column label="组长姓名" align="center" prop="userGroupName" />
      <el-table-column label="小组成员(教练)" align="center" prop="memberNames"  show-overflow-tooltip  />
      <el-table-column label="正式课承担量/单" align="center" prop="formalMax" />
<!--      <el-table-column label="正式课比例/%" align="center" prop="formalRatio" />-->
<!--      <el-table-column label="试课承担量/单" align="center" prop="testMax" />-->
<!--      <el-table-column label="试课比例/%" align="center" prop="testRatio" />-->
      <el-table-column label="企微群聊机器人" align="center" prop="botKey">
        <template slot-scope="scope">
          <span :style="{ color: scope.row.botKey ? 'green' : 'red' }">
            {{ scope.row.botKey ? '已设置' : '未设置' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['course:PayGroup:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['course:PayGroup:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改交付小组对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="125px">
        <el-form-item label="交付小组名称" prop="name" label-width="125px">
          <el-input v-model="form.name" placeholder="请输入所属交付小组" />
        </el-form-item>
        <el-form-item label="企微群聊机器人" prop="botKey" label-width="125px">
          <el-input v-model="form.botKey" placeholder="请输入企微群聊机器人设置" />
        </el-form-item>
<!--        <el-form-item label="课程分类" prop="classTypeId" label-width="125px">-->
<!--          <el-select v-model="form.classTypeId" placeholder="请选择课程分类" size="large" style="width: 240px">-->
<!--            <el-option v-for="item in classTypes" :key="item.id" :label="item.name" :value="item.id" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="接单类型" prop="orderType" label-width="125px">
          <el-select v-model="form.orderType" placeholder="请选择接单类型" size="large" style="width: 240px">
            <el-option v-for="dict in dict.type.c_order_type" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="交付组长" prop="userGroupId" label-width="125px">
          <el-select v-model="form.userGroupId" placeholder="请选择交付组长" filterable size="large" style="width: 240px">
            <el-option v-for="item in paygroups" value-key="id" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="小组成员" prop="memberIdList" label-width="125px">
          <el-select multiple @change="membersChange" v-model="form.memberIdList" placeholder="请选择小组成员" size="large"
            style="width: 240px">
            <el-option v-for="item in members"" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="正式课承担量/单" prop="formalMax" label-width="125px">
          <el-input-number size="large" v-model="form.formalMax" placeholder="请输入正式课承担量">
            <template #suffix>
              <span>单</span>
            </template>
          </el-input-number>
        </el-form-item>
<!--        <el-form-item label="正式课比例/%" prop="formalRatio" label-width="125px">-->
<!--          <el-input-number size="large" v-model="form.formalRatio" placeholder="请输入正式课比例">-->
<!--            <template #suffix>-->
<!--              <span>%</span>-->
<!--            </template>-->
<!--          </el-input-number>-->
<!--        </el-form-item>-->
        <el-form-item label="试课承担量/单" prop="testMax" label-width="125px">
          <el-input-number size="large" v-model="form.testMax" placeholder="请输入试课承担量">
            <template #suffix>
              <span>单</span>
            </template>
          </el-input-number>
        </el-form-item>
<!--        <el-form-item label="试课比例/%" prop="testRatio" label-width="125px">-->
<!--          <el-input-number size="large" v-model="form.testRatio" placeholder="请输入试课比例">-->
<!--            <template #suffix>-->
<!--              <span>%</span>-->
<!--            </template>-->
<!--          </el-input-number>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPayGroup, getPayGroup, delPayGroup, addPayGroup, updatePayGroup } from "@/api/course/PayGroup";
import { listType } from "@/api/business/kctype"
import { allCoach } from "@/api/course/Coach";
import store from "../../../store";

export default {
  name: "PayGroup",
  dicts: ['course_yes_no', 'c_order_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 交付小组表格数据
      PayGroupList: [],
      // 课程分类数据
      classTypes: [],
      paygroups: [],
      members: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        orderType: null,
        userGroupId: null,
        userGroupName: null,
        formalMax: null,
        formalRatio: null,
        testMax: null,
        testRatio: null,
      },
      payGourseParams: {
        orderType: null,
      },
      // 表单参数
      form: {
        classTypes: [],
        paygroups: [],
        members: [],
      },
      // 表单校验
      rules: {
        botKey: [
          { required: true, trigger: "blur", message: "请输入企微群聊机器人设置" }
        ],
        name: [
          { required: true, trigger: "blur", message: "请输入交付小组名称" }
        ],
        classTypeId: [
          { required: true, trigger: "change", message: "请选择课程分类" }
        ],
        orderType: [
          { required: true, trigger: "change", message: "请选择接单类型" }
        ],
        userGroupId: [
          { required: true, trigger: "change", message: "请选择交付组长" }
        ],
        memberIdList: [
          { required: true, type: 'array', trigger: "change", message: "请选择小组成员" }
        ],
        formalMax: [
          { required: true, trigger: "blur", message: "请输入正式课承担量" }
        ],
        formalRatio: [
          { required: true, trigger: "blur", message: "请输入正式课比例" }
        ],
        testMax: [
          { required: true, trigger: "blur", message: "请输入试课承担量" }
        ],
        testRatio: [
          { required: true, trigger: "blur", message: "请输入试课比例" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询交付小组列表 */
    getList() {
      this.loading = true;
      store.getters.roles.forEach(role => {
        if (role.name == '超级管理员') {
          this.queryParams.createBy = null;
        } else {
          this.queryParams.createBy = store.getters.user.userId;
        }
      });
      listPayGroup(this.queryParams).then(response => {
        this.PayGroupList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listType(this.queryParams1).then(response => {
        this.classTypes = response.rows;
      });
      allCoach({ roleType: '1' ,isNotGroup: '0'}).then(response => {
        this.paygroups = response.data;
        console.log('[ response ] >', response)
      });
      allCoach({}).then(response => {
        this.members = response.data;
        console.log('[ response ] >', response)
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        orderType: null,
        userGroupId: null,
        userGroupName: null,
        formalMax: null,
        formalRatio: null,
        testMax: null,
        testRatio: null,
        createBy: null,
        createTime: null,
        updateTime: null,
        delFlag: null,
        classTypes: [],
        paygroups: [],
        members: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加交付小组";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      allCoach({ isNotGroup: '0' }).then(response => {
        this.members = response.data;
        console.log('[ this.members ] >', this.members)
      });
      const id = row.id || this.ids
      getPayGroup(id).then(response => {
        this.form = response.data;
        const members = response.data.members;
        console.log('[ members ] >', members)
        if (members) {
          members.forEach(item => {
            this.members.push(item);
          });
        }
        // 确保 members 是数组
        // this.form.members = [];
        // if (typeof memberNames === 'string' && memberNames) {
        //   this.form.members = memberNames.split(',').filter(item => item !== '');
        // } else if (Array.isArray(memberNames)) {
        //   this.form.members = memberNames;
        // } else {
        //   this.form.members = [];
        // }
        this.open = true;
        this.title = "修改交付小组";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log('提交表单', this.form);
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePayGroup(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPayGroup(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除交付小组编号为"' + ids + '"的数据项？').then(function () {
        return delPayGroup(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('course/PayGroup/export', {
        ...this.queryParams
      }, `PayGroup_${new Date().getTime()}.xlsx`)
    },
    // 小组成员变更时可以添加逻辑处理
    membersChange(val) {
      console.log('小组成员变更:', val);
      this.form.memberIds = val.map(item => item).join(',');
      console.log('form:', this.form);
    },
  }
};
</script>
